package com.tsinghuabigdata.edu.ddmath.module.neteaseim;

import android.content.Context;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.helper.ChatRoomHelper;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;

/**
 * Created by 28205 on 2017/3/16.
 */
public class NimUserstatusManager {
    private Context context;
    private UserStatusListener listener;

    private NimUserstatusManager() {
    }

    private static class InstanceHolder {
        private static final NimUserstatusManager instance = new NimUserstatusManager();
    }

    public static final NimUserstatusManager getInstance() {
        return InstanceHolder.instance;
    }


    private void registerObservers(boolean register) {
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(userStatusObserver, register);
    }

    Observer<StatusCode> userStatusObserver = new Observer<StatusCode>() {
        @Override
        public void onEvent(StatusCode statusCode) {
            if (statusCode.wontAutoLogin()) {

                nimLogout();
                if (listener != null) {
                    listener.onLogout(statusCode);
                }
                if (context != null) {
                    AlertManager.toast(context, "已从网易云退出");
                }

            }
        }
    };

    public void nimLogout() {
        //删除本地的网易用户信息
        NeteaseAccountUtils.clear();
        NimCache.getImageLoaderKit().clear();
        ChatRoomHelper.logout();
        NimCache.clear();
        NIMClient.getService(AuthService.class).logout();
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public UserStatusListener getListener() {
        return listener;
    }

    public void setListener(UserStatusListener listener) {
        this.listener = listener;
    }

    interface UserStatusListener {
        void onLogout(StatusCode statusCode);
    }
}
